const PublicModel = require('../models/publicModelModel');
const path = require('path');
const fileUtils = require('../utils/fileUtils');
const fs = require('fs-extra');
const config = require('../config/config');

/**
 * 获取所有公共模型
 */
exports.getAllPublicModels = async () => {
    try {
        const models = await PublicModel.find({})
            .select('_id name description file.fileType thumbnail downloadCount createdAt uploadedBy')
            .sort({ createdAt: -1 });

        // 转换为前端所需格式
        const formattedModels = models.map(model => {
            const modelObj = model.toObject();
            modelObj.id = modelObj._id.toString();
            return modelObj;
        });

        return { success: true, data: formattedModels };
    } catch (error) {
        return { success: false, error: error.message };
    }
};

/**
 * 上传公共模型
 */
exports.uploadPublicModel = async (fileData, userId) => {
    try {
        const { originalname, path: filePath, size, filename } = fileData;
        const fileType = fileUtils.getFileExtension(originalname);
        
        // 验证文件类型是否为stl或obj
        if (!['stl', 'obj'].includes(fileType)) {
            await fileUtils.deleteFile(filePath);
            return { success: false, error: '不支持的文件格式，仅支持STL和OBJ格式' };
        }

        // 创建新的公共模型记录
        const newModel = new PublicModel({
            name: originalname.split('.')[0], // 使用文件名作为模型名称
            uploadedBy: userId,
            file: {
                fileName: filename,
                filePath: filePath,
                fileSize: size,
                fileType: fileType
            }
        });

        // 生成缩略图
        const thumbnailDir = path.dirname(filePath);
        const thumbnailPath = path.join(thumbnailDir, `${filename}_thumbnail.png`);
        await fileUtils.generateThumbnail(filePath, thumbnailPath);
        
        // 更新模型记录的缩略图信息
        newModel.thumbnail = {
            path: thumbnailPath,
            url: `/public-models/${newModel._id}/thumbnail`
        };

        const savedModel = await newModel.save();
        const modelObj = savedModel.toObject();

        return {
            success: true,
            data: {
                model: {
                    id: modelObj._id.toString(),
                    name: modelObj.name,
                    fileType: modelObj.file.fileType,
                    fileSize: modelObj.file.fileSize,
                    thumbnail: modelObj.thumbnail?.url
                },
                message: '公共模型上传成功'
            }
        };
    } catch (error) {
        return { success: false, error: error.message };
    }
};

/**
 * 根据ID获取公共模型
 */
exports.getPublicModelById = async (modelId) => {
    try {
        const model = await PublicModel.findById(modelId);

        if (!model) {
            return { success: false, error: '模型不存在' };
        }

        // 转换为前端所需格式
        const modelObj = model.toObject();
        modelObj.id = modelObj._id.toString();

        return { success: true, data: modelObj };
    } catch (error) {
        return { success: false, error: error.message };
    }
};

/**
 * 下载公共模型（增加下载计数）
 */
exports.downloadPublicModel = async (modelId) => {
    try {
        const model = await PublicModel.findById(modelId);

        if (!model) {
            return { success: false, error: '模型不存在' };
        }

        // 增加下载计数
        model.downloadCount += 1;
        await model.save();

        return { 
            success: true, 
            data: {
                filePath: model.file.filePath,
                fileName: model.file.fileName,
                originalName: model.name + '.' + model.file.fileType
            }
        };
    } catch (error) {
        return { success: false, error: error.message };
    }
};